<script setup>
import { ref } from 'vue'
import { userLoginServices, userRegisterServices } from '@/api/user.js'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user.js'
import { ElMessage } from 'element-plus'
const form = ref({
  username: 'limu',
  password: '123456',
  rePassword: ''
})
const formRef = ref()
const router = useRouter()
const userStore = useUserStore()
const onLogin = async () => {
  let res = await userLoginServices(form.value)
  if (res.code === 1) {
    ElMessage.error(res.message)
    return
  }
  if (res.code === 0) {
    userStore.setToken(res.data)
    router.replace('/home')
  }
}
const onRegister = (formRef) => {
  formRef.validate(async (valid) => {
    if (valid) {
      let res = await userRegisterServices(form.value)
      if (res.code === 1) {
        ElMessage.warning(res.message)
        return
      }
      ElMessage.success('注册成功')
    }
  })
}
const register = ref(false)
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码！'))
  } else if (value !== form.value.password) {
    callback(new Error('两次输入的密码不一致！'))
  } else {
    callback()
  }
}
const rules = ref({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  rePassword: [{ required: true }, { validator: validatePass2, trigger: 'blur' }]
})
</script>

<template>
  <div style="display: flex; justify-content: center">
    <el-form :model="form" ref="formRef" label-width="auto" :rules="rules">
      <el-form-item>
        <h1 v-if="!register">登录</h1>
        <h1 v-else>注册</h1>
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" v-show="register" prop="rePassword">
        <el-input type="password" v-model="form.rePassword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onLogin" v-if="!register">登录</el-button>
        <el-button type="primary" v-else @click="onRegister(formRef)">注册</el-button>
      </el-form-item>
      <el-form-item>
        <el-link :underline="false" type="info" @click="register = true" v-if="!register"
          >注册→</el-link
        >
        <el-link :underline="false" type="info" @click="register = false" v-else>←返回</el-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped></style>
